package com.genghis.ptas.security;


import com.genghis.ptas.security.entity.User;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: gaoyang
 * To change this template use File | Settings | File Templates.
 */
public class SessionListener implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent event) {
    }

    /**
     * 当用户调用session.invalidate()方法销毁session的时候,将调用此方法
     */
    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        HttpSession session = httpSessionEvent.getSession();
        ServletContext application = session.getServletContext();

        // 取得登录的用户名
        User user = (User) session.getAttribute("user");

        // 从在线列表中删除用户名
        List<String> onlineUserList = (List<String>) application.getAttribute("onlineUserList");
        if (onlineUserList.contains(user.getLoginName())) {
            onlineUserList.remove(user.getLoginName());
        }
        System.out.println(user.getLoginName() + "超时退出。");
    }

}

